const jwt = require('jsonwebtoken')
const { secret } = require('../config')
const User = require("../models/users")
class UserCtrl {

    async checkUserExist(ctx) {
        const user = await User.findById(ctx.params.id)
        if (!user) {
            ctx.throw(404, '用户不存在')
        }
    }

    async find(ctx) {
        let { per_page = 2, q = '' } = ctx.query
        let page = Math.max(ctx.query.page * 1, 1) - 1
        let perPage = Math.max(per_page * 1, 1)
        ctx.body = User
            .find({ name: new RegExp(q), gender: q })
            .limit(perPage)
            .skip(page * perPage)
    }

    async findById(ctx) {
        const { fields = '' } = ctx.query
        const selectFields = fields.split(';').filter(f => f).map(f => '+' + f).join(' ')
        const user = await User.findById(ctx.params.id).select(selectFields)
        ctx.body = user
    }

    async create(ctx) {
        ctx.verifyParams({
            name: {
                type: 'string',
                required: true
            },
            password: {
                type: 'string',
                required: true
            },
        })
        const { name } = ctx.request.body
        const repeatedUser = await User.findOne({ name })
        if (repeatedUser) {
            ctx.throw(409, '用户已存在')
        }
        const user = await new User(ctx.request.body).save()
        ctx.body = user
    }

    async update(ctx) {
        ctx.verifyParams({
            name: {
                type: 'string',
                required: false
            },
            password: {
                type: 'string',
                required: false
            },
            avatar_url: {
                type: 'string',
                required: false
            },
            gender: {
                type: 'string',
                required: false
            }
        })
        const user = await User.findByIdAndUpdate(ctx.params.id, ctx.request.body)
        ctx.body = user
    }

    async delete(ctx) {
        await User.findByIdAndDelete(ctx.params.id, ctx.request.body)
        ctx.status = 204
    }

    async login(ctx) {
        ctx.verifyParams({
            name: { type: 'string', required: true },
            password: { type: 'string', required: true }
        })
        const user = await User.findOne(ctx.request.body)
        if (!user) { ctx.throw(401, '用户名或者密码不正确') }
        const { _id, name } = user
        const token = jwt.sign({ _id, name }, secret, { expiresIn: '1d' })
        ctx.body = { token }
    }
}

module.exports = new UserCtrl()